package com.thinkgem.jeesite.modules.fantasy.web;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thinkgem.jeesite.modules.fantasy.common.constant.Constants;
import com.thinkgem.jeesite.modules.fantasy.entity.City;
import com.thinkgem.jeesite.modules.fantasy.entity.CityMap;
import com.thinkgem.jeesite.modules.fantasy.utils.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.thinkgem.jeesite.common.security.shiro.session.SessionDAO;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.fantasy.common.constant.SessionConstant;
import com.thinkgem.jeesite.modules.fantasy.entity.FantasyUser;
import com.thinkgem.jeesite.modules.fantasy.entity.FantasyUserDetail;
import com.thinkgem.jeesite.modules.fantasy.service.impl.FantasyUserService;
import com.thinkgem.jeesite.modules.sys.security.Principal;
import com.thinkgem.jeesite.modules.sys.security.UsernamePasswordToken;

@Controller
@RequestMapping(value = "fantasy/user")
public class FantasyUserController extends BaseController {
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private SessionDAO sessionDAO;
	@Autowired
	private FantasyUserService userService;

	/*
	 * 前台通过ajax验证用户名是否存在
	 */
/*	public String checkUser() {
		logger.debug("checkUser()");
		logger.debug("待验证用户名：" + username);
		message = userService.checkUser(username);
		return SUCCESS;
	}
	public String checkNickname() {
		logger.debug("checkNickname()");
		logger.debug("待验证昵称：" + nickname);
		message = userService.checkNickname(nickname);
		return SUCCESS;
	}
	
	 * 前台通过ajax验证email是否存在
	 
	public String checkEmail() {
		logger.debug("checkEmail()");
		logger.debug("待验证邮箱地址：" + email);
		message = userService.checkEmail(email);
		return SUCCESS;
	}
	
	 * 前台通过ajax获取验证码
	 
	public String checkVerifycode() {
		logger.debug("checkVerifycode()");
	    message = (String) session.get("rand");
		logger.debug("session中的验证码：" + message);
		return SUCCESS;
	}
	
	 * 注册功能
	 
	public String register() {
		logger.debug("register()");
		String message = userService.register(user);
		logger.debug(message);
		if (message == "user_exist"){
			session.put("message", "用户名已存在。");
			return ERROR;
		} else if (message =="email_exist") {
			session.put("message", "邮箱已存在。");
			return ERROR;
		} else if (message == "register_no"){
			session.put("message", "用户注册失败。");
			return ERROR;
		} else if (message == "send_error"){
			session.put("message", "邮件发送失败。");
			return ERROR;
		} else if (message == "send_ok") {
			session.put("message", message);
			session.put("currentUser", user);
			return SUCCESS;
		} else {
			session.put("message", "未捕获异常。");
			return ERROR;
		}
	}
	
	 * 邮箱未验证前再次发送邮件
	 
	public String sendEmail() {
		logger.debug("sendEmail()");
		logger.debug(authFor);
		User user = (User) session.get("currentUser");
		logger.debug("currentUser " + user);
		String message = userService.sendEmail(user, authFor);
		logger.debug(message);
		session.put("message", message);
		//session.put("currentUser", user);
		if ("send_ok".equals(message)) {
			return SUCCESS;
		} else {
			return ERROR;
		}
	}
	
	 * 登陆功能
	 
	public String login() {
		logger.debug("login()");

    	message = userService.checkUser(user.getUsername());
		logger.debug(message);
		if ("user_available".equals(message)) {
			message = "用户名不存在。";
			return INPUT;
		} else {
			user = userService.login(user);
			if (user != null) {
				logger.debug("user.getUsername() = " + user.getUsername());
				logger.debug(user.getEmail());
				logger.debug("user.getHomePoint() = " + user.getHomePoint());
				session.put("currentUser", user);
				session.put("homepoint", user.getHomePoint());
				
				//登陆成功后，登陆次数+1，同时记录当前登陆时间。
				UserDetail detail = userService.getDetailByUserId(user.getId());
				userService.changeUserLogintimes(detail.getId(), detail.getLogintimes());
				session.put("begintime", new Date());
				
				
				//登陆成功后，调用Action movetohome
				return SUCCESS;
			} else {
				message = "用户名或密码错误。";
				return INPUT;
			}
		}
	}
	
	 * 登出，删除session，以后可以增加对cookie的删除
	 
	public String logout() {
		logger.debug("logout()");
		//session.remove("currentUser");
		User user = (User) session.get("currentUser");
		if (user == null) {
    		logger.debug("用户非法");
    		request.put("message", "用户非法");
    		return ERROR;
    	} else {
    		logger.debug("userid = " + user.getId());
            Date beginTime = (Date) session.get("begintime");
    		int tempTime = (int) (new Date().getTime() - beginTime.getTime())/1000;
    		logger.info(user.getUsername() + "本次登陆时间：" + tempTime);
        	int userid = user.getId();
        	UserDetail detail = userService.getDetailByUserId(userid);
        	userService.changeUserLandingtime(detail.getId(), detail.getLandingtime(), tempTime);
    	}
		
		session.clear();
		return SUCCESS;
	}
	
	public String showAllAttr() {
		logger.debug("showAllAttr()");
    	User user = (User) session.get("currentUser");
		if (user == null) {
    		logger.debug("用户非法");
    		request.put("message", "用户非法");
    		return ERROR;
    	} else {
    		logger.debug("userid = " + user.getId());
    		Property prop = userService.getPropByUserId(user.getId());
    		request.put("property", prop);
    		UserDetail detail = userService.getDetailByUserId(user.getId());
    		request.put("detail", detail);
    	}
		return SUCCESS;
	}*/
    

	/**
	 * 登录示例
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/login")
	@ResponseBody
	public Object login(HttpServletRequest request) {
		Map<String, String> returnMap = new HashMap<String, String>();
		String errInfo = "";
		if (logger.isDebugEnabled()){
			logger.debug("login, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}
		
		try {
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			String sessionCode = (String) session.getAttribute(SessionConstant.LOGIN_CODE);

			// 此处默认有值
			String username = request.getParameter("username");
			if(username.indexOf("：") != -1){
				username = username.replace("：", ":");
			}
			String inputcode = request.getParameter("inputcode");
			String password = request.getParameter("password");
			if (null == inputcode || "".equals(inputcode)
					|| !inputcode.equalsIgnoreCase(sessionCode)) {
				errInfo = "nullcode";
			} else if (username == null) {
				errInfo = "null";
			} else if (StringUtils.loginFilter(username)) {
				errInfo = "specialchar";
			} else {
				UsernamePasswordToken token = new UsernamePasswordToken(
						username, password.toCharArray(), true, StringUtils.getRemoteAddr((HttpServletRequest)request), inputcode, false);

				//if (!currentUser.isAuthenticated()) {
					token.setRememberMe(true);
					currentUser.login(token);
				//}
				errInfo = "success";
				Principal principal = (Principal) currentUser.getPrincipal();
				Integer logintype = principal.getLogintype();
				if (logintype == 1) {//fantasy用户登录
					returnMap.put("logintype", "1");
					// 将登录对象保存在session中
					FantasyUser operator = userService.selectUser(username);
					session.setAttribute(SessionConstant.LOGIN_USER, operator);
					
					logger.debug("user.getUsername() = " + operator.getUsername());
					logger.debug(operator.getEmail());
					logger.debug("user.getHomePoint() = " + operator.getHomePoint());
					session.setAttribute("homepoint", operator.getHomePoint());
					
					//登陆成功后，登陆次数+1，同时记录当前登陆时间。
					FantasyUserDetail detail = userService.getDetailByUserId(operator.getId());
					userService.changeUserLogintimes(detail.getId(), detail.getLogintimes());
					session.setAttribute("begintime", new Date());

					//登陆成功后，保存用户信息到redis中，key为用户id
					redisUtil.setValue(Constants.REDIS_USER_ + operator.getId(), operator);
					//初始化用户的所在城市 重复了，放在回家的操作中进行2018.7.17 wanghui
					//userService.moveUser(operator, operator.getHomePoint());
				} else {//jeesite用户登录
					returnMap.put("logintype","2");
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			errInfo = "error";
		}
		returnMap.put("result", errInfo);
		return returnMap;
	}

	/**
	 * 登出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public ModelAndView logout() {
		logger.debug("logout()");
    	ModelAndView mv = new ModelAndView();
		Subject currentUser = SecurityUtils.getSubject();
		Date beginTime = (Date) currentUser.getSession().getAttribute("begintime");
		if (beginTime != null) {
			int tempTime = (int) (new Date().getTime() - beginTime.getTime())/1000;
			Principal principal = (Principal) currentUser.getPrincipal();
			
			logger.info(principal.getName() + "本次登陆时间：" + tempTime);
	    	String userid = principal.getId();
	    	FantasyUserDetail detail = userService.getDetailByUserId(userid);
	    	userService.changeUserLandingtime(detail.getId(), detail.getLandingtime(), tempTime);

			//登陆成功后，保存用户信息到redis中，key为用户id
			redisUtil.delValue(userid);
			currentUser.logout();
		}
		mv.setViewName("modules/fantasy/login");
		
		
		return mv;
	}
    
    /**
     * 输出验证码
     * @param response
     */
	@RequestMapping("/code")
	public void generate(HttpServletResponse response) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String code = drawImg(output);

		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		session.setAttribute(SessionConstant.LOGIN_CODE, code);

		try {
			ServletOutputStream out = response.getOutputStream();
			output.writeTo(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 生成验证码
	 * @param output
	 * @return
	 */
	private String drawImg(ByteArrayOutputStream output) {
		String code = "";
		for (int i = 0; i < 4; i++) {
			code += randomChar();
		}
		int width = 70;
		int height = 25;
		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.TYPE_3BYTE_BGR);
		Font font = new Font("Times New Roman", Font.PLAIN, 20);
		Graphics2D g = bi.createGraphics();
		g.setFont(font);
		Color color = new Color(66, 2, 82);
		g.setColor(color);
		g.setBackground(new Color(226, 226, 240));
		g.clearRect(0, 0, width, height);
		FontRenderContext context = g.getFontRenderContext();
		Rectangle2D bounds = font.getStringBounds(code, context);
		double x = (width - bounds.getWidth()) / 2;
		double y = (height - bounds.getHeight()) / 2;
		double ascent = bounds.getY();
		double baseY = y - ascent;
		g.drawString(code, (int) x, (int) baseY);
		g.dispose();
		try {
			ImageIO.write(bi, "jpg", output);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return code;
	}

	/**
	 * 生成随机数字和英文字符
	 * @return
	 */
	private char randomChar() {
		Random r = new Random();
		String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
		return s.charAt(r.nextInt(s.length()));
	}
	
	
}
